package linkedtable;

/**
 * @Description 剑指 Offer II 021. 删除链表的倒数第 n 个结点
 * @Author Firenut
 * @Date 2023-02-03 22:40
 */
public class T021_removeNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head.next==null&&n==1){
            return null;
        }
        ListNode pre,cur,after;
        ListNode ahead=new ListNode(); //设置虚结点方便操作
        ahead.next=head;
        pre=ahead;
        cur=after=head;
        while(n-->1){
            after=after.next;
        }
        while(after.next!=null){
            pre=pre.next;
            cur=cur.next;
            after=after.next;
        }
        pre.next=cur.next;
        if(cur==head){
            return pre.next;
        }
        return head;
    }

}
